package com.tsing.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class FileUtil {

    private final static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /**
     * MultipartFile转File
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        if (file.equals("") || file.getSize() <= 0) {
            return null;
        } else {
            InputStream is = file.getInputStream();
            File result = new File(file.getOriginalFilename());
            inputStreamToFile(is, result);
            is.close();
            return result;
        }
    }

    //获取流文件
    private static void inputStreamToFile(InputStream is, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            is.close();
        } catch (Exception e) {
            logger.error("inputstream 转 file报错:{}", e.getMessage());
        }
    }

    public static MultipartFile fileToMultipartFile(File file) throws Exception {
        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(new FileInputStream(file)));
        return multipartFile;
    }

    public static final InputStream byteToInputStream(byte[] buff) {
        return new ByteArrayInputStream(buff);
    }

    public static ByteArrayInputStream outputStreamToByteArrayInputStream(OutputStream out) {
        ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
        return new ByteArrayInputStream(baos.toByteArray());
    }

    public static String imgToBase64(byte[] file) {
        return "data:image/JPEG;base64," + Base64.encodeBase64String(file);
    }

    public static String pdfToBase64(byte[] file) {
        return "data:application/pdf;base64," + Base64.encodeBase64String(file);
    }

    public static String svgToBase64(byte[] file) {
        return "data:image/svg+xml;base64," + Base64.encodeBase64String(file);
    }

}
